//
//  DetaillNewsController.swift
//  网易新闻
//
//  Created by wl on 15/11/16.
//  Copyright © 2015年 wl. All rights reserved.
//  新闻详情界面看控制器
/***************************************************
*  如果您发现任何BUG,或者有更好的建议或者意见，请您的指教。
*邮箱:wxl19950606@163.com.感谢您的支持
***************************************************/
import UIKit
import SVProgressHUD
let PlayerButtonDidClikNotification = "PlayerButtonDidClikNotification"

class DetaillNewsController: UIViewController, UITextFieldDelegate, RGFadeDelegate, UITableViewDelegate, UITableViewDataSource,UIWebViewDelegate, DetailCPTJFooterViewDelegate, DetailHYZXFooterViewDelegate, DetailVideoFooterViewDelegate,DetailTaoBaoFooterViewDelegate,
    CLMXFooterViewDelegate, DetailShareViewDelegate, UIActionSheetDelegate{
//========================================================
// MARK: - 一些属性
//========================================================
    var newsModel: NewsModel?
    var newsDetailModel: NewsDetailModel? {
        didSet {
            self.tableView.reloadData()
            self.initRightItem()
            self.rightItem()
            self.rgFadeView?.docid = newsDetailModel?.docid
            loadNewsDetail()
            
        }
    }
    var webView: UIWebView!
    /// 展示新闻的view
    @IBOutlet weak var tableView: UITableView!

   
    @IBOutlet weak var buttomView_hyzx: UIView!

    var webHeight: CGFloat = 0.0
    /// 正在播放视频的URL
    var playingNewsUrl: String = ""
    /// 正在播放视频的播放器
    var playingPlayer: WLVideoPlayerView?
    
    var playerView: NewsDetailVideo?
    
    //视频
    lazy var controlView = {
        return NSBundle.mainBundle().loadNibNamed("PlayerControlView", owner: nil, options: nil).last as! PlayerControlView
    }()
    //只有搜藏和转发
    lazy var cptjFooterView = {
        return NSBundle.mainBundle().loadNibNamed("DetailCPTJFooterView", owner: nil, options: nil).last as! DetailCPTJFooterView
        
    }()
    //评论。收藏。转发。
    lazy var hyzxFooterView = {
        return NSBundle.mainBundle().loadNibNamed("DetailHYZXFooterView", owner: nil, options: nil).last as! DetailHYZXFooterView
    }()
    //直播新闻
    lazy var videoFooterView = {
         return NSBundle.mainBundle().loadNibNamed("DetailVideoFooterView", owner: nil, options: nil).last as! DetailVideoFooterView
    }()
    //淘宝新闻
    lazy var taobaoFooterView = {
        return NSBundle.mainBundle().loadNibNamed("DetailTaoBaoFooterView", owner: nil, options: nil).last as! DetailTaoBaoFooterView
    }()
    //享乐美学
    lazy var clmxFooterView = {
        return NSBundle.mainBundle().loadNibNamed("CLMXFooterView", owner: nil, options: nil).last as! CLMXFooterView
        
    }()
    var commentView: CommentView?
    
    var rgFadeView: RGFadeView?
    
    var shareView: DetailShareView?
    
    var isshoucang: Bool?
    
    var type: String?
    
    var msg: regiestInfo?
    
    var actionSheet: UIActionSheet? = nil
    var fontSize: Int?
//========================================================
// MARK: - 一些方法
//========================================================
    override func viewDidLoad() {
        super.viewDidLoad()
        publicMethod.setHUDStyle()
        self.webView = UIWebView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 1))
        publicMethod.hiddleExtendCellForTableView(self.tableView)
        self.webView.delegate = self
        self.webView.scrollView.scrollEnabled = false
        self.automaticallyAdjustsScrollViewInsets = false
        self.webView.backgroundColor = UIColor.whiteColor()
        self.tabBarController?.tabBar.hidden = true
        self.tableView.delegate = self
        self.tableView.dataSource = self
        //self.tableView.separatorStyle = UITableViewCellEditingStyleNone
        
        //self.textField.delegate = self
        //字体大小
        let str = ApplicationDelegate.fontSize()
        self.fontSize  =  Int( (str as NSString).intValue)
        
        assert(self.newsModel?.docid != nil)
        // 加载本地缓存数据
//        if let newsDetailModel = LocalDataTool.getNewsDetailInfo(self.newsModel!.docid!) as? NewsDetailModel {
//            self.newsDetailModel = newsDetailModel
//        }
        
        let cellNib = UINib(nibName: "NewsDetailWebCell", bundle: nil)
        
        self.tableView.registerNib(cellNib, forCellReuseIdentifier: "NewsDetailWebCell")
        
        let cellNib1 = UINib(nibName: "NewsDetailHotReplyCell1", bundle: nil)
        
        self.tableView.registerNib(cellNib1, forCellReuseIdentifier: "NewsDetailHotReplyCell1")
        
        let cellNib2 = UINib(nibName: "ExtensionADCell", bundle: nil)
        
        self.tableView.registerNib(cellNib2, forCellReuseIdentifier: "ExtensionADCell")
        
        self.playerView = NSBundle.mainBundle().loadNibNamed("NewsDetailVideo", owner: nil, options: nil).last as? NewsDetailVideo
        
        //播放视频
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DetaillNewsController.playNewsVideo(_:)), name: PlayerButtonDidClikNotification, object: nil)
        
        

        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DetaillNewsController.webViewHeight(_:)), name: webViewHeight_noti, object: nil)
        
         NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DetaillNewsController.userTouched_noti(_:)), name: userHeadClicked_noti, object: nil)
       
        self.getDetailInfo()
        
    }
    //MARK:noti
    func userTouched_noti(notification:NSNotification){
        
        let id = notification.object?.valueForKey("id") as! String
        
        self.userTouched(Int(id)!)
        
    }
    //头像点击
    func userTouched(userID: Int) {
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("UserHomeTableViewController") as! UserHomeTableViewController
        vc.userId = userID
        
        self.navigationController?.pushViewController(vc, animated: true)
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillAppear(animated)
        self.playingPlayer?.removeFromSuperview()
        self.playingPlayer = nil
         SVProgressHUD.dismiss()
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
       
    }
    
    /**
     析构方法
     */
    deinit {
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
       /**
     重置播放器的一些参数,在重新刷新数据、当前控制器失去焦点的时候调用的时候调用
     */
    func resetPlayer() {
        self.playingPlayer?.removeFromSuperview()
        self.playingPlayer = nil
        
    }
    /**
     视频播放通知事件的回调函数，在点击某一个cell的播放按钮的时候调用，
     进行视频新闻播放
     - parameter notification: 一些播放视频所需要的信息
     */
    func playNewsVideo(notification: NSNotification) {
        

        self.playingPlayer?.removeFromSuperview()
        
        self.playingPlayer = nil
        
        self.playingPlayer = WLVideoPlayerView(url: NSURL(string: (self.newsModel?.videosrc)!))
        self.playingPlayer?.customControlView = controlView
        self.playingPlayer?.placeholderView = UIImageView(image: UIImage(named: "placeholder"))
        self.playingPlayer?.playInView(self.playerView!)
        
    }
    //转发按钮点击事件
    func transBtnClicked(sender: UIButton){
        let shareParames = NSMutableDictionary()
        var url: String!
        if self.newsModel?.tname == "专题新闻"{
            if ApplicationDelegate.selectedChanelName() == "行业资讯"{
                url = String(format: "%@infomation/fenxiang/\(self.newsDetailModel!.docid)",BaseUrl)
            }
            if ApplicationDelegate.selectedChanelName() == "产品推荐"{
                url = String(format: "%@product/fenxiang/\(self.newsDetailModel!.docid)",BaseUrl)
            }
            if ApplicationDelegate.selectedChanelName() == "享乐美学"{
                url = String(format: "%@xlmx/fenxiang/\(self.newsDetailModel!.docid)",BaseUrl)
            }
            
        }
        if self.newsModel?.tname == "行业资讯"{
             url = String(format: "%@infomation/fenxiang/\(self.newsDetailModel!.docid)",BaseUrl)
        }
        if self.newsModel?.tname == "产品推荐"{
            url = String(format: "%@product/fenxiang/\(self.newsDetailModel!.docid)",BaseUrl)
        }
        if self.newsModel?.tname == "享乐美学"{
            url = String(format: "%@xlmx/fenxiang/\(self.newsDetailModel!.docid)",BaseUrl)
        }
        
        shareParames.SSDKSetupShareParamsByText("",
                                                images : UIImage(named: "ShareImg.png"),
                                                url : NSURL(string:url),
                                                title : self.newsDetailModel?.title,
                                                type : SSDKContentType.Auto)
        
        
        //2.进行分享
        SSUIShareActionSheetStyle.setShareActionSheetStyle(ShareActionSheetStyle.Simple)
        
        ShareSDK.showShareActionSheet(sender, items: nil  , shareParams: shareParames) { (state : SSDKResponseState, platformType : SSDKPlatformType, userdata : [NSObject : AnyObject]!, contentEnity : SSDKContentEntity!, error : NSError!, end) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: self.showAlert("分享成功")
            case SSDKResponseState.Fail:
            self.showAlert("分享失败")// print("分享失败,错误描述:\(error)")
            case SSDKResponseState.Cancel:  self.showAlert("分享取消")//print("分享取消")
                
            default:
                break
            }
        }
        

    }
    //收藏按钮点击事件
    @IBAction func collectBtnDown(sender: UIButton) {
        DataTool.collectionNews((self.newsDetailModel?.docid)!,isshoucang:self.isshoucang!,type:self.type!, completionHandler: { (newsData)
            in
            guard let newsDetailData = newsData else {
            return
            }
            self.msg = newsDetailData
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
            self.getDetailInfo()
        })
    }
    
    func initWebView(){
        self.webView = UIWebView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 1))
        self.webView.delegate! = self
        self.webView.scrollView.scrollEnabled = false

    }
    //跳转到评论页
    @IBAction func commenBtnClicked(sender: UIButton){
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("CommentViewController") as! CommentViewController
        vc.requestID = self.newsDetailModel?.docid
        vc.type = "行业"
        vc.isshoucang = self.newsDetailModel?.isshoucang
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //分享按钮target
    @IBAction func setShareBtnClicked(sender: UIButton){
          sender.selected = !sender.selected
        if sender.selected{
            shareView = DetailShareView.init(frame: kScreen_frame)
            shareView?.delegate = self
            self.view.addSubview(shareView!)
        }else{
            shareView?.closeBtnClick()
        }
        
        
    }
   //MARK:出现键盘
    
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        //self.textField.resignFirstResponder()
        
        //let isFirst = self.commentView?.becomeFirstResponder()
        
        //print("isfirst = \(isFirst)")
        if (rgFadeView == nil) {
            rgFadeView = RGFadeView.init(frame: kScreen_frame)
            //rgFadeView?.docid = newsDetailModel?.docid
            rgFadeView?.delegate = self
            self.view.addSubview(rgFadeView!)
        }
        rgFadeView?.msgTextView.becomeFirstResponder()
        

        return true
    }
    
    //MARK:DetailCPTJFooterViewDelegate
    func collectionSelected(sender: UIButton){
        if ApplicationDelegate.isLogin(){
            if self.newsDetailModel?.isshoucang == true{
                self.isshoucang = false
            }else{
                self.isshoucang = true
            }
            self.collectBtnDown(sender)
 
        }else{
            let sb = UIStoryboard(name: "Login", bundle: nil)
            let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    func transmitSelected(sender: UIButton){
        
        self.transBtnClicked(sender)
    }
    //MARK:DetailHYZXFooterViewDelegate
    func HYZXCollectionBtnSelected(sender: UIButton){
        if ApplicationDelegate.isLogin(){
            if self.newsDetailModel?.isshoucang == true{
                self.isshoucang = false
            }else{
                self.isshoucang = true
            }
            
            self.collectBtnDown(sender)
        }else{
            let sb = UIStoryboard(name: "Login", bundle: nil)
            let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
    func HYZXcommentBtnSelected(sender: UIButton){
        self.commenBtnClicked(sender)
    }
    func HYZXtransmitBtnSelected(sender: UIButton){
         self.transBtnClicked(sender)
    }

    //MARK:DetailVideoFooterViewDelegate
    func VideocollectionBtnSelected(sender: UIButton){
        if ApplicationDelegate.isLogin(){
            if self.newsDetailModel?.isshoucang == true{
                self.isshoucang = false
            }else{
                self.isshoucang = true
            }
            
            self.collectBtnDown(sender)
        }else{
            let sb = UIStoryboard(name: "Login", bundle: nil)
            let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
    
    func VideowatchBtnSelected(sender: UIButton){
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("DetailTaoboaAndliveVideoVC") as! DetailTaoboaAndliveVideoVC
        vc.urlStr = self.newsDetailModel!.url3w!
    self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func VideotransmitBtnSelected(sender: UIButton){
         self.transBtnClicked(sender)
    }
    
    //MARK:DetailTaoBaoFooterViewDelegate
    func taobaoBtnSelected(sender: UIButton){
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("DetailTaoboaAndliveVideoVC") as! DetailTaoboaAndliveVideoVC
        vc.urlStr = self.newsDetailModel!.url3w!
       
        self.navigationController?.pushViewController(vc, animated: true)
    }
    func taobaoCollectionSelected(sedner: UIButton){
        if ApplicationDelegate.isLogin(){
            if self.newsDetailModel?.isshoucang == true{
                self.isshoucang = false
            }else{
                self.isshoucang = true
            }
            
            self.collectBtnDown(sedner)
        }else{
            let sb = UIStoryboard(name: "Login", bundle: nil)
            let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
            self.navigationController?.pushViewController(vc, animated: true)
        }

    }
    func taobaoReplySelected(sedner: UIButton){
        self.commenBtnClicked(sedner)
    }
    func taobaoTransferSelected(sender: UIButton){
        self.transBtnClicked(sender)
    }
    //MARK:CLMXFooterViewDelegate
    func CLMXcollectionSelected(sender: UIButton){
        if ApplicationDelegate.isLogin(){
            if self.newsDetailModel?.isshoucang == true{
                self.isshoucang = false
            }else{
                self.isshoucang = true
            }
            
            self.collectBtnDown(sender)
        }else{
            let sb = UIStoryboard(name: "Login", bundle: nil)
            let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    func CLMXtransmitSelected(sender: UIButton){
         self.transBtnClicked(sender)
    }
    
    func CLMXreplySelected(sender: UIButton){
        self.commenBtnClicked(sender)
    }
    //MARK:DetailShareViewDelegate
    func wechatCircle(){
        if publicMethod.isWechat(){
            let shareParames = NSMutableDictionary()
            let url =  String(format: "%@infomation/fenxiang/\(self.newsDetailModel!.docid)",BaseUrl)
            shareParames.SSDKSetupShareParamsByText("",
                                                    images : UIImage(named: "ShareImg.png"),
                                                    url : NSURL(string: url),
                                                    title : self.newsDetailModel?.title,
                                                    type : SSDKContentType.Auto)
            
            
            //2.显示分享编辑页面
            ShareSDK.showShareEditor(SSDKPlatformType.SubTypeWechatTimeline, otherPlatformTypes: nil, shareParams: shareParames) { (state :SSDKResponseState, platformType : SSDKPlatformType , userData: [NSObject : AnyObject]!, contentEntity : SSDKContentEntity!, error : NSError!, end) -> Void in
                
                switch state{
                    
                case SSDKResponseState.Success: self.showAlert("分享成功")
                case SSDKResponseState.Fail:    self.showAlert("分享失败")
                case SSDKResponseState.Cancel: self.showAlert("分享取消")

                    
                default:
                    break
                }
            }

        }else{
            self.showAlert("您还没有安装微信")

        }
        
    }
    func wechatFriend(){
        if publicMethod.isWechat(){
            let shareParames = NSMutableDictionary()
            let url =  String(format: "%@infomation/fenxiang/\(self.newsDetailModel!.docid)",BaseUrl)
            shareParames.SSDKSetupShareParamsByText("",
                                                    images : UIImage(named: "ShareImg.png"),
                                                    url : NSURL(string: url),
                                                    title : self.newsDetailModel?.title,
                                                    type : SSDKContentType.Auto)
            
            
            //2.显示分享编辑页面
            ShareSDK.showShareEditor(SSDKPlatformType.SubTypeWechatSession, otherPlatformTypes: nil, shareParams: shareParames) { (state :SSDKResponseState, platformType : SSDKPlatformType , userData: [NSObject : AnyObject]!, contentEntity : SSDKContentEntity!, error : NSError!, end) -> Void in
                
                switch state{
                    
                case SSDKResponseState.Success: self.showAlert("分享成功")
                case SSDKResponseState.Fail:    self.showAlert("分享失败")
                case SSDKResponseState.Cancel: self.showAlert("分享取消")
                    
                default:
                    break
                }
            }

        }else{
            self.showAlert("您还没有安装微信")
        }
        
        
    }
    func qqFriend(){
        if publicMethod.isQQ(){
            let shareParames = NSMutableDictionary()
            let url =  String(format: "%@infomation/fenxiang/\(self.newsDetailModel!.docid)",BaseUrl)
            shareParames.SSDKSetupShareParamsByText("",
                                                    images : UIImage(named: "ShareImg.png"),
                                                    url : NSURL(string: url),
                                                    title : self.newsDetailModel?.title,
                                                    type : SSDKContentType.Auto)
            
            
            //2.显示分享编辑页面
            ShareSDK.showShareEditor(SSDKPlatformType.SubTypeQQFriend, otherPlatformTypes: nil, shareParams: shareParames) { (state :SSDKResponseState, platformType : SSDKPlatformType , userData: [NSObject : AnyObject]!, contentEntity : SSDKContentEntity!, error : NSError!, end) -> Void in
                
                switch state{
                    
                case SSDKResponseState.Success: self.showAlert("分享成功")
                case SSDKResponseState.Fail:    self.showAlert("分享失败")
                case SSDKResponseState.Cancel: self.showAlert("分享取消")
                default:
                    break
                }
            }

        }else{
            self.showAlert("你还没有安装QQ")
        }
        
        
    }
    func qqZone(){
        if publicMethod.isQQ(){
            let shareParames = NSMutableDictionary()
            let url =  String(format: "%@infomation/fenxiang/\(self.newsDetailModel!.docid)",BaseUrl)
            shareParames.SSDKSetupShareParamsByText("",
                                                    images : UIImage(named: "ShareImg.png"),
                                                    url : NSURL(string: url),
                                                    title : self.newsDetailModel?.title,
                                                    type : SSDKContentType.Auto)
            
            
            //2.显示分享编辑页面
            ShareSDK.showShareEditor(SSDKPlatformType.SubTypeQZone, otherPlatformTypes: nil, shareParams: shareParames) { (state :SSDKResponseState, platformType : SSDKPlatformType , userData: [NSObject : AnyObject]!, contentEntity : SSDKContentEntity!, error : NSError!, end) -> Void in
                
                switch state{
                    
                case SSDKResponseState.Success: self.showAlert("分享成功")
                case SSDKResponseState.Fail:    self.showAlert("分享失败")
                case SSDKResponseState.Cancel: self.showAlert("分享取消")
                    
                default:
                    break
                }
            }

        }else{
            self.showAlert("您还没有安装QQ")
           
        }
        
        
    }
    func weibo(){
        let shareParames = NSMutableDictionary()
        let url =  String(format: "%@infomation/fenxiang/\(self.newsDetailModel!.docid)",BaseUrl)
        shareParames.SSDKSetupShareParamsByText(url,
                                                images : UIImage(named: "ShareImg.png"),
                                                url : NSURL(string:url),
                                                title : self.newsDetailModel?.title,
                                                type : SSDKContentType.Auto)
        //2.显示分享编辑页面
        ShareSDK.showShareEditor(SSDKPlatformType.TypeSinaWeibo, otherPlatformTypes: nil, shareParams: shareParames) { (state :SSDKResponseState, platformType : SSDKPlatformType , userData: [NSObject : AnyObject]!, contentEntity : SSDKContentEntity!, error : NSError!, end) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: self.showAlert("分享成功")
            case SSDKResponseState.Fail:    self.showAlert("分享失败")
            case SSDKResponseState.Cancel: self.showAlert("分享取消")
                
            default:
                break
            }
        }
        
    
    }
    func foneSize(){
        if (actionSheet == nil) {
            self.actionSheet = UIActionSheet(title: "选择字体大小",delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles:"特大", "大", "中","小")
        }
        self.actionSheet!.showInView(self.view!)
        
    }
    func report(){
        
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("ReportVC") as! ReportVC
        vc.id = self.newsDetailModel!.docid
        self.navigationController?.pushViewController(vc, animated: true)
        
        
    }
    func collection(){
        if ApplicationDelegate.isLogin(){
            if self.newsDetailModel?.isshoucang == true{
                self.isshoucang = false
            }else{
                self.isshoucang = true
            }
            
            DataTool.collectionNews((self.newsDetailModel?.docid)!,isshoucang:self.isshoucang!,type:self.type!, completionHandler: { (newsData)
                in
                guard let newsDetailData = newsData else {
                    return
                }
                self.msg = newsDetailData
                self.getDetailInfo()
                SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
               
                
            })

        }else{
            let sb = UIStoryboard(name: "Login", bundle: nil)
            let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
            self.navigationController?.pushViewController(vc, animated: true)
        }
       
       
    }
    //MARK:actionSheetDelegate
    func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 1 {
            //大
            print("特大")
           
            NSUserDefaults.standardUserDefaults().setObject("20" , forKey:"fontSizeDefaut")
            
        }else if buttonIndex == 2 {
            //大
            print("大")
            
            NSUserDefaults.standardUserDefaults().setObject("18" , forKey:"fontSizeDefaut")
            
        }else if buttonIndex == 3{
            //中
            print("中")
            
            NSUserDefaults.standardUserDefaults().setObject("16" , forKey:"fontSizeDefaut")
            
        }else{
            //小
            print("小")
            
            NSUserDefaults.standardUserDefaults().setObject("14" , forKey:"fontSizeDefaut")
        }
        
    }

    //MARK:tableviewDataSource
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }

     func tableView(tableView: UITableView, editingStyleForRowAt indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
        
        return UITableViewCellEditingStyle.None
        
    }
    func tableView(tableView: UITableView,heightForHeaderInSection section: Int) -> CGFloat{
        if self.newsModel?.videosrc != ""{
            return 150
        }else{
            return 0
        }
        
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let sectionView = UIView()
         self.playerView?.frame = CGRectMake(0, 0, SCREEN_WIDTH, 150)
        sectionView.addSubview(self.playerView!)
       //默认为true
    if ApplicationDelegate.isAutolive() {
        
        if ApplicationDelegate.isWifi(){
             NSNotificationCenter.defaultCenter().postNotificationName(PlayerButtonDidClikNotification, object: self, userInfo: nil)
            }
    }else{
         NSNotificationCenter.defaultCenter().postNotificationName(PlayerButtonDidClikNotification, object: self, userInfo: nil)
        }
        return sectionView
        
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.newsModel?.tname == "行业资讯" || self.newsModel?.tname == "享乐美学" {
            if self.newsDetailModel?.rmlist?.count != 0 && self.newsDetailModel?.rmlist?.count != nil {
                return 3
            } else {
                return 2
            }
        } else {
            return 1
        }

    }


    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 0{
            if self.newsDetailModel == nil{
                return 0
            }else{
                return webView.frame.size.height
            
            }
            
        }else if indexPath.row == 1 {
            if newsDetailModel?.adsimgsrc == "" || newsDetailModel?.adsimgsrc == nil{
                return 0
            } else {
                return 150
            }
           
            
        } else {
            if self.newsDetailModel?.rmlist?.count == nil || self.newsDetailModel?.rmlist?.count == 0{
                return 0
            }else{
                var height:CGFloat = 0.0
                for index in 0...(self.newsDetailModel?.rmlist?.count)! - 1 {
                    
                    let font = UIFont(name: "Helvetica", size: 16)
                    
                    height += publicMethod.getLabHeigh((newsDetailModel?.rmlist![index].message)!, font: font!, width: SCREEN_WIDTH - 16) + 65
                    
                }
                return height + 30
            }

        }
    
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.row == 0{
            let cell = tableView.dequeueReusableCellWithIdentifier("NewsDetailWebCell") as! NewsDetailWebCell
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            cell.addSubview(webView)
            return cell
        }else if indexPath.row == 1{
            let cell = tableView.dequeueReusableCellWithIdentifier("ExtensionADCell") as! ExtensionADCell
            if newsDetailModel?.adsimgsrc != nil {
                cell.ADIv.sd_setImageWithURL(NSURL(string: (newsDetailModel!.adsimgsrc)), placeholderImage: UIImage(named: "placeholder"))
            }
            
            return cell
            
            
        } else {
            let cell = tableView.dequeueReusableCellWithIdentifier("NewsDetailHotReplyCell1") as! NewsDetailHotReplyCell1
            let cellInfo = self.newsDetailModel?.rmlist
            cell.setCellContentWithCellInfo(cellInfo)
            return cell

        }
        

    }

    // MARK: - Table view delegate
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if self.newsDetailModel?.adsurl != "" {
            if indexPath.row == 1 {
                let vc = self.storyboard?.instantiateViewControllerWithIdentifier("DetailTaoboaAndliveVideoVC") as! DetailTaoboaAndliveVideoVC
                
                vc.urlStr = (self.newsDetailModel?.adsurl)!
                self.navigationController?.pushViewController(vc, animated: true)
            }
           
        }
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    //MARK: webViewLoadInfo
    /**
     这里用来显示被点击的那一张图片
     */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let str = request.URL?.absoluteString
        if let temp = str?.componentsSeparatedByString("=") where temp.count > 1{
            DetailPictureView.showAtWindow(self.newsDetailModel!, index: Int(temp.last!)!)
        }
        
        return true
    }
    
    /**
     加载描述界面
     */
    func loadNewsDetail() {
        
        assert(self.newsDetailModel != nil)
        let css = NSBundle.mainBundle().URLForResource("Details.css", withExtension: nil)!
        
        var html = "<html>"
        
        html += "<head>"
        html += "<link rel=\"stylesheet\" href="
        html += "\"\(css)\""
        html += ">"
        html += "</head>"
        
        html += self.getBody()
        html += "</html>"
        
        self.webView.loadHTMLString(html, baseURL: nil)
        
    }
    /**
     被loadNewsDetail方法调用，用来拼接<body>的内容
     */
    func getBody() -> String{
        
        var body = "<body style='font-size: \(self.fontSize! + 2)px'>"
        
        body += "<div class=\"title\" style='font-size: \(self.fontSize! + 10)px'>"
       
      
        body += self.newsDetailModel!.title
        body += "</div>"
        body += "<table width='400' border='0' cellspacing='0' cellpadding='0'>"
        body += "<tbody>"
        body += "<tr>"
        body += "<td  width='50' rowspan='2'><img src='\(self.newsDetailModel!.timg)' width='50' height='50' alt=''/></td>"
        body += "<td height='30' style='padding-left:10px'>"
        body += "\(self.newsDetailModel!.contributor)"
        body += "</td>"
        body += "</tr>"
        body += "<tr>"
        body += "<td height='30' style='padding-left:10px;font-size:12px;'><span style='padding:2px; border:1px solid #000000;border-radius:3px;'>"
        body += "\(self.newsDetailModel!.tags)"
        body += "</span>"
        body += "\(self.newsDetailModel!.ptime)"
        body += "</td>"
        body += "</tr>"
        body += "</tbody>"
        body += "</table>"

        body += self.newsDetailModel!.body
        
        for (index, detailImageModel) in self.newsDetailModel!.img.enumerate() {
            var imgTag = "<div class=\"image\">"
            
            imgTag += "<img id=\"\(index)\" "
            
            //用 * 符号切割字符串，"haha*hehe*xixi" ==>  "haha" "hehe" "xixi"
            let pixel = detailImageModel.pixel.componentsSeparatedByString("*")
            
            var width = Float(pixel.first!) ?? 0
            var height = Float(pixel.last!) ?? 0
            
            let maxWidth = Float(SCREEN_WIDTH * 0.95)
            if width > maxWidth {
                height =  height *  maxWidth / width
                width = maxWidth
            }
            
            // 这里是添加图片点击事件
            imgTag += "onload="
            imgTag += "\""
            imgTag += "this.onclick = function() {  window.location.href = 'sx:index=' +this.id;};"
            imgTag += "\""
            
            imgTag += "width=\(width) "
            imgTag += "height=\(height) "
            imgTag += "src=\(detailImageModel.src)>"
            
            imgTag += "<div class=\"imageDetail\">"
            imgTag += "\(detailImageModel.alt)"
            imgTag += "</div>"
            
            
            imgTag += "</div>"
            
            // 替换位置
            body = body.stringByReplacingOccurrencesOfString(detailImageModel.ref, withString: imgTag)
        }
        
        body += "</body>"
        
        return body
    }
    //MARK: webViewDelegate
    func webViewDidFinishLoad(webView: UIWebView) {
        
        let webHeightStr = webView.stringByEvaluatingJavaScriptFromString("document.body.scrollHeight")
        
        let webHeight:CGFloat = CGFloat((webHeightStr! as NSString).floatValue)
        
        self.webView.frame = CGRect(x: self.webView.frame.origin.x, y: self.webView.frame.origin.y, width: SCREEN_WIDTH, height: webHeight)
        
        self.tableView.reloadData()
    }

    //MARK:RGFadeViewDelegate
    func sendBtnDown(text: String) {
        if ApplicationDelegate.isLogin(){
            let jsonData = ["docid": (newsModel?.docid)!, "message": text]
            DataTool.sendComment(jsonData,type: "", completionHandler: { (isSuccess) -> Void in
                if isSuccess {
                    let vc = self.storyboard?.instantiateViewControllerWithIdentifier("CommentViewController") as! CommentViewController
                    vc.requestID =  self.newsDetailModel!.docid
                    vc.type = "行业"
                    self.navigationController?.pushViewController(vc, animated: true)
                } else {
                    print("failed")
                }
            })
        }else{
            SVProgressHUD.showInfoWithStatus("请先登录")
        }
        
    }
    func cptj_footer(){
        self.type = "产品推荐"
        cptjFooterView.frame.size.width = SCREEN_WIDTH
        buttomView_hyzx.addSubview(cptjFooterView)
        if self.newsDetailModel?.isshoucang == true{
            cptjFooterView.collectionBtn.setImage(UIImage(named: "collection_selected"), forState: UIControlState.Normal)
        }else{
            cptjFooterView.collectionBtn.setImage(UIImage(named: "collection_grey"), forState: UIControlState.Normal)
        }
        cptjFooterView.delegate = self
    }
    func hyzx_footer(){
        self.type = "行业资讯"
        if self.newsModel?.type == 6{
            videoFooterView.frame.size.width = SCREEN_WIDTH
            buttomView_hyzx.addSubview(videoFooterView)
            if self.newsDetailModel?.isshoucang == true{
                videoFooterView.collectionBtn.setImage(UIImage(named: "collection_selected"), forState: UIControlState.Normal)
            }else{
                videoFooterView.collectionBtn.setImage(UIImage(named: "collection_grey"), forState: UIControlState.Normal)
            }
            
            
            videoFooterView.delegate = self
        }else{
            self.type = "行业资讯"
            hyzxFooterView.frame.size.width = SCREEN_WIDTH
            hyzxFooterView.textField.delegate = self
            
            buttomView_hyzx.addSubview(hyzxFooterView)
            
            if self.newsDetailModel?.isshoucang == true{
                hyzxFooterView.collectionBtn.setImage(UIImage(named: "collection_selected"), forState: UIControlState.Normal)
            }else{
                hyzxFooterView.collectionBtn.setImage(UIImage(named: "collection_grey"), forState: UIControlState.Normal)
            }
            hyzxFooterView.delegate = self
        }

    }
    func xlmx_footer(){
        self.type = "享乐美学"
        if self.newsModel?.type == 8{
            taobaoFooterView.frame.size.width = SCREEN_WIDTH
            buttomView_hyzx.addSubview(taobaoFooterView)
            if self.newsDetailModel?.isshoucang == true{
                taobaoFooterView.collectionBtn.setImage(UIImage(named: "collection_selected"), forState: UIControlState.Normal)
            }else{
                taobaoFooterView.collectionBtn.setImage(UIImage(named: "collection_grey"), forState: UIControlState.Normal)
            }
            taobaoFooterView.textfield.delegate = self
            taobaoFooterView.delegate = self
        }else{
            
            clmxFooterView.frame.size.width = SCREEN_WIDTH
            buttomView_hyzx.addSubview(clmxFooterView)
            clmxFooterView.textfield.delegate = self
            if self.newsDetailModel?.isshoucang == true{
                clmxFooterView.collectionBtn.setImage(UIImage(named: "collection_selected"), forState: UIControlState.Normal)
            }else{
                clmxFooterView.collectionBtn.setImage(UIImage(named: "collection_grey"), forState: UIControlState.Normal)
            }
            clmxFooterView.delegate = self
        }

    }
    //MARK: showSuccessAlert
    func showAlert(message: String){
        let alertView = UIAlertView(title: "", message: message, delegate: nil, cancelButtonTitle: "确定" )
        
        alertView.show()
    }
    //MARK:initRightItem
    func initRightItem(){
        if self.newsModel?.tname == "专题新闻"{
            if ApplicationDelegate.selectedChanelName() == "产品推荐"{
                cptj_footer()
            }
            if ApplicationDelegate.selectedChanelName() == "行业资讯"{
                self.hyzx_footer()
            }
            if ApplicationDelegate.selectedChanelName() == "享乐美学"{
                self.xlmx_footer()
            }
            
        }
        if self.newsModel?.tname == "产品推荐" || self.newsModel?.tname == "系统消息"{
           self.cptj_footer()
        }
        if self.newsModel?.tname == "行业资讯"{
            self.hyzx_footer()
        }
        if self.newsModel?.tname == "享乐美学"{
            self.xlmx_footer()
        }

    }
    //MARK:noti
    func webViewHeight(note:NSNotification){
        let fd = (note.object?.valueForKey("height") )
        
        webHeight = CGFloat ( (fd as! NSString).floatValue)
        
        let indexPath = NSIndexPath(forRow: 0, inSection: 0)
        
        self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
        
    }
    //MARK: networking
    func getDetailInfo(){
        if self.newsModel?.tname == "享乐美学"{
            SVProgressHUD.showWithStatus("加载中...")
            let urlStr = String(format: "%@xlmx/",BaseUrl)
            DataTool.loadNewsDetailDataEx(self.newsModel!.docid!,url: urlStr) { (newsModel) -> Void in
                guard newsModel != nil else {
                    return
                }
                SVProgressHUD.dismiss()
                self.newsDetailModel = newsModel
                // 本地存储
//                LocalDataTool.saveNewsDetailInfo(self.newsModel!.docid!, anyModel: newsModel!)
            }
            
            
            
        }else if self.newsModel?.tname == "行业资讯"{
            SVProgressHUD.showWithStatus("加载中...")
            let urlStr = String(format: "%@infomation/",BaseUrl)
            DataTool.loadNewsDetailDataEx(self.newsModel!.docid!,url: urlStr) { (newsModel) -> Void in
                guard newsModel != nil else {
                    return
                }
                SVProgressHUD.dismiss()
                self.newsDetailModel = newsModel
                // 本地存储
//                LocalDataTool.saveNewsDetailInfo(self.newsModel!.docid!, anyModel: newsModel!)
            }//产品推荐
        }else if self.newsModel?.tname == "产品推荐" || self.newsModel?.tname == "系统消息"{
            SVProgressHUD.showWithStatus("加载中...")
            let urlStr = String(format: "%@product/",BaseUrl)
            DataTool.loadNewsDetailDataEx(self.newsModel!.docid!,url: urlStr) { (newsModel) -> Void in
                guard newsModel != nil else {
                    return
                }
                SVProgressHUD.dismiss()
                self.newsDetailModel = newsModel
                // 本地存储
//                LocalDataTool.saveNewsDetailInfo(self.newsModel!.docid!, anyModel: newsModel!)
            }
        }else{
            SVProgressHUD.showWithStatus("加载中...")
        }

    }
    func rightItem(){
        let shareBtn = UIButton(frame: CGRectMake(0, 0, 25, 25))
        shareBtn.setBackgroundImage(UIImage(named: "right_item")!, forState: UIControlState.Normal)
        shareBtn.addTarget(self, action: #selector(self.setShareBtnClicked), forControlEvents:  UIControlEvents.TouchUpInside)
        let share = UIBarButtonItem(customView: shareBtn)
        self.navigationItem.rightBarButtonItem = share

    }
    
}
// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com